<template>
  <div class="article-comments">
    <!-- 评论列表 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
    >
      <!-- 组件化 -->
      <comment-item
        v-for="(item, index) in list"
        :key="index"
        :item="item"
        @toggleLiked="
          item.is_liking = !item.is_liking
          item.like_count = item.like_count + $event
        "
      ></comment-item>
    </van-list>
    <!-- 评论列表 -->

    <!-- 发布评论 -->
    <van-cell-group class="publish-wrap">
      <van-field clearable placeholder="请输入评论内容">
        <van-button slot="button" size="mini" type="info">发布</van-button>
      </van-field>
    </van-cell-group>
    <!-- /发布评论 -->
  </div>
</template>

<script>
// 导入获取评论的api
import { getArtCommnet } from '@/assets/api/comment'
// 导入评论item组件
import commentItem from './comment-cell.vue'
// 导入通信组件
import eventHub from '@/assets/utils/communication'

export default {
  name: 'ArticleComment',
  props: {
    art_id: {
      type: [String, Number, Object],
      required: true
    }
  },
  data() {
    return {
      list: [], // 评论列表
      loading: false, // 上拉加载更多的 loading
      finished: false, // 是否加载结束
      // 获取评论的请求参数
      commentParams: {
        type: 'a',
        source: this.art_id.toString(),
        offset: undefined,
        limit: undefined
      },
      // 列表错误提示
      error: false,
      total_count: 0
    }
  },
  methods: {
    async onLoad() {
      // 获取评论
      try {
        // 发起请求
        var { data: res } = await getArtCommnet(this.commentParams)
      } catch {
        // 处理错误请求
        this.error = true
        this.loading = false
        this.$toast('获取评论失败，稍后再试')
      }
      // 将请求赋值给本地
      this.commentParams.offset = res.data.last_id
      this.total_count = res.data.total_count
      this.list.push(...res.data.results)
      // 关闭loading
      this.loading = false

      // 把评论总数传给父组件
      this.$emit('sendBadge', this.total_count)
      // 判断是否还有数值
      if (!res.data.last_id) {
        this.finished = true
      }
    }
  },
  mounted() {
    this.onLoad()
    eventHub.$on('addComment', (val) => {
      this.list.unshift(val)
    })
  },
  components: {
    'comment-item': commentItem
  }
}
</script>

<style scoped lang="less">
.publish-wrap {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
}

.van-list {
  margin-bottom: 45px;
}
</style>
